package com.qst.rongxiaotong.handler;


import com.qst.rongxiaotong.common.Result;
import com.qst.rongxiaotong.exception.BaseException;
import com.qst.rongxiaotong.exception.MessageConstant;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

import lombok.extern.slf4j.Slf4j;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return new Result(false,10000,ex.getMessage());
    }

    @ExceptionHandler
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error("异常信息：{}", ex.getMessage());
        String errorMsg = ex.getMessage();
        if (errorMsg.contains("Duplicate entry")) {
            String[] errorList = errorMsg.split(" ");
            return new Result(false,10000,errorList[2] + MessageConstant.ALREADY_EXIST);
        } else {
            return new Result(false,10000,MessageConstant.UNKNOWN_ERROR);
        }
    }
}
